package com.yougou.ui.product;

import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.yougou.R;
import com.yougou.base.BaseActivity;
import com.yougou.data.model.Goods;
import com.yougou.data.model.GoodsDetail;
import com.yougou.ui.product.adapter.ProductImageAdapter;
import com.yougou.utils.FavoriteManager;
import com.yougou.utils.ToastUtils;

import java.util.List;
import java.util.Locale;

public class ProductDetailActivity extends BaseActivity {
    
    public static final String EXTRA_GOODS_ID = "goods_id";
    
    private ImageView mBtnBack;
    private ImageView mIvFavorite;
    private ViewPager2 mImageViewPager;
    private TextView mTvPrice;
    private TextView mTvName;
    private WebView mWebViewDescription;
    private Button mBtnAddCart;
    private Button mBtnBuyNow;
    
    private ProductImageAdapter mImageAdapter;
    private ProductDetailViewModel mViewModel;
    private int mGoodsId;
    private GoodsDetail mCurrentDetail;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        
        // 获取商品ID
        mGoodsId = getIntent().getIntExtra(EXTRA_GOODS_ID, 0);
        
        initView();
        initData();
    }
    
    @Override
    protected void initView() {
        mBtnBack = findViewById(R.id.iv_back);
        mIvFavorite = findViewById(R.id.iv_favorite);
        mImageViewPager = findViewById(R.id.viewpager_images);
        mTvPrice = findViewById(R.id.tv_product_price);
        mTvName = findViewById(R.id.tv_product_name);
        mWebViewDescription = findViewById(R.id.webview_product_description);
        mBtnAddCart = findViewById(R.id.btn_add_cart);
        mBtnBuyNow = findViewById(R.id.btn_buy_now);
        
        // 初始化图片适配器
        mImageAdapter = new ProductImageAdapter();
        mImageViewPager.setAdapter(mImageAdapter);
        
        // 配置WebView
        WebSettings webSettings = mWebViewDescription.getSettings();
        webSettings.setJavaScriptEnabled(false);  // 禁用JavaScript提高安全性
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        
        // 允许从网络加载图片
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setBlockNetworkImage(false);
        
        // 允许混合内容（HTTPS页面加载HTTP资源）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        
        // 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        
        // 返回按钮
        mBtnBack.setOnClickListener(v -> finish());
        
        // 收藏按钮
        mIvFavorite.setOnClickListener(v -> toggleFavorite());
        
        // 加入购物车
        mBtnAddCart.setOnClickListener(v -> {
            GoodsDetail detail = mViewModel.getGoodsDetail().getValue();
            mViewModel.addToCart(detail);
        });
        
        // 立即购买
        mBtnBuyNow.setOnClickListener(v -> {
            GoodsDetail detail = mViewModel.getGoodsDetail().getValue();
            mViewModel.buyNow(detail);
        });
    }
    
    @Override
    protected void initData() {
        mViewModel = new ViewModelProvider(this).get(ProductDetailViewModel.class);
        
        // 观察商品详情
        mViewModel.getGoodsDetail().observe(this, detail -> {
            if (detail != null) {
                updateUI(detail);
            } else {
                ToastUtils.show(this, "商品详情加载失败");
            }
        });
        
        // 观察加载状态
        mViewModel.isLoading().observe(this, loading -> {
            if (loading != null && loading) {
                // 可以在这里显示加载进度条
                ToastUtils.show(this, "正在加载商品详情...");
            }
        });
        
        // 观察消息
        mViewModel.getMessage().observe(this, message -> {
            if (message != null && !message.isEmpty()) {
                ToastUtils.show(this, message);
            }
        });
        
        // 观察是否需要登录
        mViewModel.getNeedLogin().observe(this, needLogin -> {
            if (needLogin != null && needLogin) {
                // 跳转到登录页面
                android.content.Intent intent = new android.content.Intent(this, com.yougou.ui.login.LoginActivity.class);
                startActivity(intent);
            }
        });
        
        // 观察立即购买
        mViewModel.getBuyNowData().observe(this, detail -> {
            if (detail != null) {
                // 跳转到订单确认页面
                android.content.Intent intent = new android.content.Intent(this, com.yougou.ui.order.OrderConfirmActivity.class);
                intent.putExtra(com.yougou.ui.order.OrderConfirmActivity.EXTRA_GOODS_ID, detail.getGoodsId());
                intent.putExtra(com.yougou.ui.order.OrderConfirmActivity.EXTRA_GOODS_NAME, detail.getGoodsName());
                intent.putExtra(com.yougou.ui.order.OrderConfirmActivity.EXTRA_GOODS_PRICE, detail.getGoodsPrice());
                // 传递商品图片
                List<String> picUrls = detail.getPicUrls();
                if (picUrls != null && !picUrls.isEmpty()) {
                    intent.putExtra(com.yougou.ui.order.OrderConfirmActivity.EXTRA_GOODS_IMAGE, picUrls.get(0));
                }
                intent.putExtra(com.yougou.ui.order.OrderConfirmActivity.EXTRA_QUANTITY, 1);
                startActivity(intent);
            }
        });
        
        // 加载商品详情
        if (mGoodsId > 0) {
            mViewModel.loadGoodsDetail(mGoodsId);
        } else {
            ToastUtils.show(this, "商品ID无效");
            finish();
        }
    }
    
    
    private void updateUI(GoodsDetail detail) {
        mCurrentDetail = detail;
        
        // 设置价格
        mTvPrice.setText(String.format(Locale.CHINA, "¥%.2f", detail.getGoodsPrice()));
        
        // 设置名称
        mTvName.setText(detail.getGoodsName());
        
        // 设置描述 - 使用WebView加载HTML内容
        String htmlContent = detail.getGoodsIntroduce();
        if (htmlContent != null && !htmlContent.isEmpty()) {
            htmlContent = htmlContent.replace("src=\"//", "src=\"https://");
            htmlContent = htmlContent.replace("data-src=\"//", "data-src=\"https://");
            
            String wrappedHtml = "<html><head>" +
                    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                    "<style>" +
                    "body { margin: 0; padding: 0; font-size: 14px; } " +
                    "img { max-width: 100% !important; height: auto !important; } " +
                    "p { margin: 8px 0; }" +
                    "</style>" +
                    "</head><body>" +
                    htmlContent +
                    "</body></html>";
            mWebViewDescription.loadDataWithBaseURL(null, wrappedHtml, "text/html", "UTF-8", null);
        } else {
            mWebViewDescription.loadData("暂无商品详情", "text/html", "UTF-8");
        }
        
        // 设置图片
        List<String> picUrls = detail.getPicUrls();
        if (picUrls != null && !picUrls.isEmpty()) {
            mImageAdapter.setData(picUrls);
        }
        
        // 更新收藏状态
        updateFavoriteIcon();
    }
    
    
    private void toggleFavorite() {
        if (mCurrentDetail == null) {
            ToastUtils.show(this, "商品信息未加载完成");
            return;
        }
        
        boolean isFavorite = FavoriteManager.isFavorite(mCurrentDetail.getGoodsId());
        
        if (isFavorite) {
            // 取消收藏
            FavoriteManager.removeFavorite(mCurrentDetail.getGoodsId());
            ToastUtils.show(this, "已取消收藏");
        } else {
            // 添加收藏
            Goods goods = convertToGoods(mCurrentDetail);
            FavoriteManager.addFavorite(goods);
            ToastUtils.show(this, "收藏成功");
        }
        
        updateFavoriteIcon();
    }
    
    
    private void updateFavoriteIcon() {
        if (mCurrentDetail == null) return;
        
        boolean isFavorite = FavoriteManager.isFavorite(mCurrentDetail.getGoodsId());
        
        if (isFavorite) {
            mIvFavorite.setImageResource(R.drawable.ic_favorite_filled);
            mIvFavorite.setColorFilter(getResources().getColor(R.color.color_price));
        } else {
            mIvFavorite.setImageResource(R.drawable.ic_favorite);
            mIvFavorite.setColorFilter(getResources().getColor(R.color.white));
        }
    }
    
    
    private Goods convertToGoods(GoodsDetail detail) {
        Goods goods = new Goods();
        goods.setGoodsId(detail.getGoodsId());
        goods.setGoodsName(detail.getGoodsName());
        goods.setGoodsPrice(detail.getGoodsPrice());
        
        // 设置图片 - 保存到多个字段以确保显示
        List<String> picUrls = detail.getPicUrls();
        if (picUrls != null && !picUrls.isEmpty()) {
            String imageUrl = picUrls.get(0);
            goods.setGoodsPic(imageUrl);
            goods.setGoodsSmallLogo(imageUrl);
            goods.setGoodsBigLogo(imageUrl);
        }
        
        return goods;
    }
}
